package com.yunc.modules.deploy.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.utils.R;
import com.yunc.modules.deploy.entity.Deploy;
import com.yunc.modules.deploy.service.IDeployService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * 部署表 前端控制器
 * yum install lsof
 *
 * @author concong tao
 * @since 2020-03-11
 */
@RestController
@RequestMapping("/deploy")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DeployController {

    private final IDeployService deployService;

    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermi('deploy:list')")
    public R page(Page<Deploy> page, Deploy deploy) {
        QueryWrapper<Deploy> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        deployService.page(page, qw);
        return R.ok().put("data", page.getRecords()).put("count", page.getTotal());
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("@ss.hasPermi('deploy:list')")
    public R info(@PathVariable String id) {
        Deploy deploy = deployService.getById(id);
        return R.ok().put("deploy", deploy);
    }

    @PostMapping("/save")
    @PreAuthorize("@ss.hasPermi('deploy:save')")
    public R save(Deploy deploy) {
        boolean flag = deployService.save(deploy);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @PutMapping("/update")
    @PreAuthorize("@ss.hasPermi('deploy:update')")
    public R update(Deploy deploy) {
        boolean flag = deployService.updateById(deploy);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @PostMapping("/status/{id}")
    public R statusServer(@PathVariable @NotBlank(message = "主键不能为空") String id) {
        return deployService.statusServer(id);
    }

    @PostMapping("/start/{id}")
    public R startServer(@PathVariable @NotBlank(message = "主键不能为空") String id) {
        return deployService.startServer(id);
    }

    @PostMapping("/stop/{id}")
    public R stopServer(@PathVariable @NotBlank(message = "主键不能为空") String id) {
        return deployService.stopServer(id);
    }

    @DeleteMapping("/delete/{ids}")
    @PreAuthorize("@ss.hasPermi('deploy:delete')")
    public R delete(@PathVariable String ids) {
        List<String> idsList = StrSpliter.splitTrim(ids, ',', true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = deployService.removeByIds(idsList);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}